package com.qn.web.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Map;

/**
 * @since 2020/10/3 8:36   @author 老周  @version 1.00
 * Description ${description}
 */
@WebFilter(filterName = "EncodingFilter", urlPatterns = "/*")
public class EncodingFilter implements Filter {


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        //空方法
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
        //1.强转
        HttpServletRequest request=(HttpServletRequest) req;
        HttpServletResponse response=(HttpServletResponse) resp;
        //2.放行
        chain.doFilter(new MyRequest(request), response);
    }

    @Override
    public void destroy() {
       //空方法
    }

}

//上面的MyRequest增强了request.getParameter("name");方法
//增强了所有的获取参数的方法request.getParameterValues("name");
//增强了所有的获取参数的方法request.getParameterMap();
class MyRequest extends HttpServletRequestWrapper {
    private HttpServletRequest request;
    private boolean flag=true;


    public MyRequest(HttpServletRequest request) {
        super(request);
        this.request=request;
    }

    /**
     * @param name:
     * @return java.lang.String
     * @author: 老周
     * @since: 2020/10/3 8:40
     * Description: 对单个参数进行处理
     */
    @Override
    public String getParameter(String name) {
        //进行非空控制，并去除字符串首尾空格
        if(name==null || name.trim().length()==0){
            return null;
        }
        String[] values = getParameterValues(name);
        if(values==null || values.length==0){
            return null;
        }
        //返回第一个得到的
        return values[0];
    }

    /**
     * @param name:
     * @return java.lang.String[]
     * @author: 老周
     * @since: 2020/10/3 8:42
     * Description: 对getParameterValues("name")这种数组进行处理
     */
    @Override
    public String[] getParameterValues(String name) {
        if(name==null || name.trim().length()==0){
            return null;
        }
        Map<String, String[]> map = getParameterMap();
        if(map==null || map.size()==0){
            return null;
        }

        return map.get(name);
    }

    /**
     * @param :
     * @return java.util.Map<java.lang.String, java.lang.String [ ]>
     * @author: 老周
     * @since: 2020/10/3 8:46
     * Description:  对map进行处理
     *      * map{ username=[tom],password=[123],hobby=[eat,drink]}
     */
    @Override
    public Map<String,String[]> getParameterMap() {

        /**
         * 首先判断请求方式
         * 若为post  request.setchar...(utf-8)
         * 若为get 将map中的值遍历编码就可以了
         */
        String method = request.getMethod();
        if("post".equalsIgnoreCase(method)){
            try {
                request.setCharacterEncoding("utf-8");
                return request.getParameterMap();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }else if("get".equalsIgnoreCase(method)){
            Map<String,String[]> map = request.getParameterMap();
            if(flag){
                for (String key:map.keySet()) {
                    String[] arr = map.get(key);
                    //继续遍历数组
                    for(int i=0;i<arr.length;i++){
                        //编码
                        try {
                            arr[i]=new String(arr[i].getBytes("iso-8859-1"),"utf-8");
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }
                    }
                }
                flag=false;
            }
            //需要遍历map 修改value的每一个数据的编码
            return map;
        }

        return super.getParameterMap();
    }


}
